package lemon.dog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lemon.dog.common.ErrorEnum;
import lemon.dog.common.R;
import lemon.dog.domain.User;
import lemon.dog.service.UserService;
import lemon.dog.mapper.UserMapper;
import lemon.dog.util.JwtUtil;
import lemon.dog.vo.LoginVo;
import org.springframework.stereotype.Service;

import java.util.HashMap;

/**
* @author Lemon
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2024-06-01 16:55:15
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Override
    public R login(LoginVo user) {
        LambdaQueryWrapper<User> wr = new LambdaQueryWrapper<>();
        wr.eq(User::getUserPhone, user.getPhone());
        // TODO: 密码加密处理
        wr.eq(User::getUserPassword, user.getPassword());
        User res = this.baseMapper.selectOne(wr);
        if (res == null) {
            return R.error(ErrorEnum.USER_LOGIN_ERROR);
        }
        HashMap<String, Object> data = new HashMap<>();
        data.put("token", JwtUtil.getJwtToken(res));
        return R.success(data);
    }

    @Override
    public R register(LoginVo user) {
        String phone = user.getPhone();

        String password = user.getPassword();
        String captcha = user.getCaptcha();
        LambdaQueryWrapper<User> wr = new LambdaQueryWrapper<>();
        wr.eq(User::getUserPhone, phone);
        User obj = this.baseMapper.selectOne(wr);
        if(obj != null) {
            return R.error(ErrorEnum.USER_EXIST);
        }
        User newUser = new User();
        newUser.setUserPhone(phone);
        newUser.setUserPassword(password);
        save(newUser);
        return R.success("注册成功");
    }
}




